import os
from configparser import ConfigParser
import requests
import json
from loguru import logger

APP_ID = 'cli_a615d6ffa0a31013'
APP_SECRET = 'JU94bADhJ2UTsQWRYDcQ7bo1DvFyAx8a'
INI_FILE_NAME = rf'{os.path.dirname(__file__)}/feishu_auth.ini'
SECTION = 'token'


class FeiShuAuthorization:

    def __init__(self):
        self.config = ConfigParser()
        self.config.read(INI_FILE_NAME)
        self.refresh_token = str()
        self.tenant_access_token = str()
        self.user_access_token = str()

    def get_tenant_access_token(self):
        # 该token有效期为2hours，剩下0.5hours才支持刷新，即是重新获取
        # self.tenant_access_token = data.get('tenant_access_token')
        # self.config.set(SECTION, 'tenant_access_token', self.tenant_access_token)
        # with open(INI_FILE_NAME, 'w') as f:
        #     self.config.write(f)

        url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'
        payload = json.dumps({'app_id': APP_ID, 'app_secret': APP_SECRET})
        headers = {'Content-Type': 'application/json'}

        response = requests.post(url, headers=headers, data=payload)
        print(response.status_code)
        if response.status_code != 200:
            print(f'get tenant res: {response.text}, status code: {response.status_code}')
            return
        data = response.json()
        tenant_access_token = data.get('tenant_access_token')
        logger.debug(f'Get tenant_access_token success: {data}')
        return tenant_access_token

    def get_user_access_token(self):
        url = "https://open.feishu.cn/open-apis/authen/v1/oidc/access_token"
        payload = json.dumps({
            "code": "4d8i960187b743c1a6baf762cc5920d0",  # 登录授权重定向后携带的code,失效得重新登录获取,有效期5分钟
            "grant_type": "authorization_code"
        })
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {self.tenant_access_token}'
        }
        response = requests.post(url, headers=headers, data=payload)
        if response.status_code != 200:
            print(f'get user access res: {response.text}, status code: {response.status_code}')
        data = response.json()
        print(f'get user access res: {data}')

    def refresh_user_access_token(self):
        url = "https://open.feishu.cn/open-apis/authen/v1/oidc/refresh_access_token"

        payload = json.dumps({
            "grant_type": "refresh_token",
            "refresh_token": self.config.get(SECTION, 'refresh_token')  # 有效期30天左右
        })
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {self.tenant_access_token}'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        if response.status_code != 200:
            print(f'refresh access res: {response.text}, status code: {response.status_code}')
            return
        data = response.json()
        print(f'refresh user access res: {data}')
        self.user_access_token = data.get('data').get('access_token')
        self.refresh_token = data.get('data').get('refresh_token')
        self.config.set(SECTION, 'user_access_token', self.user_access_token)
        self.config.set(SECTION, 'refresh_token', self.refresh_token)
        with open(INI_FILE_NAME, 'w') as f:
            self.config.write(f)


def update_feishu_auth_task():
    feishu_auth = FeiShuAuthorization()
    feishu_auth.get_tenant_access_token()
    # feishu_auth.get_user_access_token()
    feishu_auth.refresh_user_access_token()
